//
//  RegisterKindsChooseViewController.m
//  WEIMO
//
//  Created by Lixiaoyong on 13-7-15.
//  Copyright (c) 2013年 广州从兴电子开发有限公司. All rights reserved.
//

#import "RegisterKindsChooseViewController.h"

#import <QuartzCore/QuartzCore.h>

#import "JSONKit.h"
#import "DLog.h"
#import "KeyValueObject.h"
#import "UIUnderlinedButton.h"
#import "ConferViewController.h"

@interface RegisterKindsChooseViewController ()
@property (nonatomic,retain) UITableView *userTypeTableView;        //父分类
@property (nonatomic,retain) NSMutableArray *userTypeDatas;

@property (nonatomic,retain) UITableView *typeDetailTableView;      //子分类
@property (nonatomic,retain) NSMutableArray *typeDetailDatas;

@property (nonatomic,assign) NSInteger selectedFatherRow;           //记录选择的父分类
@property (nonatomic,retain) NSMutableArray *selectedTypes;         //记录选中的类别
@end

@implementation RegisterKindsChooseViewController
@synthesize userTypeTableView,typeDetailTableView;
@synthesize userTypeDatas,typeDetailDatas,selectedTypes;
@synthesize selectedFatherRow;
@synthesize delegate;
@synthesize firstMenuParentId;

- (void)dealloc
{
    self.userTypeTableView = nil;
    self.typeDetailTableView = nil;
    self.userTypeDatas = nil;
    self.typeDetailDatas = nil;
    self.selectedTypes = nil;
    self.delegate = nil;
    self.firstMenuParentId = nil;
    [super dealloc];
}

- (id)init
{
    self = [super init];
    if (self)
    {
        float width = self.view.frame.size.width;
        float height= self.view.frame.size.height - 44.0;
        
        CGRect rect = CGRectMake(0, 0, width*0.4, height);
        self.userTypeTableView = [[[UITableView alloc] initWithFrame:rect] autorelease];
        self.userTypeTableView.backgroundColor = [UIColor colorWithRed:235/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
        self.userTypeTableView.tag = 901;
        self.userTypeTableView.dataSource = self;
        self.userTypeTableView.delegate   = self;
        self.userTypeTableView.scrollEnabled = NO;
        self.userTypeTableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:self.userTypeTableView];
        
        rect.origin.x = rect.origin.x + rect.size.width + 5;
        rect.size.width = width - rect.origin.x - 20;
        self.typeDetailTableView = [[[UITableView alloc] initWithFrame:rect] autorelease];
        self.typeDetailTableView.backgroundColor = [UIColor clearColor];
        self.typeDetailTableView.tag = 902;
        self.typeDetailTableView.dataSource = self;
        self.typeDetailTableView.delegate   = self;
        self.typeDetailTableView.scrollEnabled = NO;
        self.typeDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.typeDetailTableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:self.typeDetailTableView];
        
        rect.origin.y = rect.origin.y + rect.size.height;
        rect = CGRectMake(0, rect.origin.y, width, 2);
        UILabel *sepLine = [[[UILabel alloc] initWithFrame:rect] autorelease];
        sepLine.backgroundColor = [UIColor grayColor];
        [sepLine.layer setShadowColor:[UIColor blackColor].CGColor];
        [sepLine.layer setShadowOffset:CGSizeMake(rect.size.width, 3.0)];
        [sepLine.layer setShadowOpacity:1.0];
        [self.view addSubview:sepLine];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    self.title = @"分类选择";
    self.view.backgroundColor = [UIColor colorWithRed:0Xdb/255.0 green:0Xdd/255.0 blue:0Xe7/255.0 alpha:1.0];
    self.selectedFatherRow = -1;
    
    //[self getUserTypeDatasFromLocalJson];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self hideKindsChooseTabBar];
    
    [self getUserTypeDatasFromLocalJson];
    
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    NSMutableArray *needReturnArray = [[[NSMutableArray alloc] init] autorelease];
    
    if (self.selectedTypes.count > 0)
    {
        KeyValueObject *kind = [self.userTypeDatas objectAtIndex:self.selectedFatherRow];
        [needReturnArray addObject:kind];
        
        for (int i=0; i<self.selectedTypes.count; i++)
        {
            KeyValueObject *item = [self.selectedTypes objectAtIndex:i];
            [needReturnArray addObject:item];
        }
    }
    
    if (self.delegate)
    {
        [self.delegate returnChoosedRegisterIdentifier:needReturnArray];
    }
}

#pragma mark - private methods

//隐藏TabBar
- (void)hideKindsChooseTabBar
{
    if (self.tabBarController.tabBar.hidden == YES)
    {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
}

//获取json数据
- (void)getUserTypeDatasFromLocalJson
{
    self.userTypeDatas = [[[NSMutableArray alloc] init] autorelease];
    
    DLog(@"parentId : %@",self.firstMenuParentId);
    
    if ([self.firstMenuParentId isEqualToString:@"1"])
    {
        self.userTypeDatas = [self getUserDatasFromLocalJsonWithKey:@"0"];
        
        for (int i=0; i<self.userTypeDatas.count; i++)
        {
            KeyValueObject *item = [self.userTypeDatas objectAtIndex:i];
            if (!([item.key isEqualToString:@"1"] || [item.key isEqualToString:@"21"] ||
                  [item.key isEqualToString:@"41"] || [item.key isEqualToString:@"61"]) )
            {
                [self.userTypeDatas removeObjectAtIndex:i];
                i--;
            }
        }
    }
    else if ([self.firstMenuParentId isEqualToString:@"2"])
    {
        KeyValueObject *item = [[KeyValueObject alloc] init];
        item.key = @"101";
        item.keyDispName = @"演艺资源";
        item.value = @"0";
        [self.userTypeDatas addObject:item];
        [item release];
    }
    else if([self.firstMenuParentId isEqualToString:@"5"])
    {
        self.userTypeDatas = [self getUserDatasFromLocalJsonWithKey:@"0"];
        for (int i=0; i<self.userTypeDatas.count; i++)
        {
            KeyValueObject *item = [self.userTypeDatas objectAtIndex:i];
            if (!([item.key isEqualToString:@"1"] || [item.key isEqualToString:@"21"] ||
                  [item.key isEqualToString:@"41"] || [item.key isEqualToString:@"61"] ||
                  [item.key isEqualToString:@"101"]) )
            {
                [self.userTypeDatas removeObjectAtIndex:i];
                i--;
            }
        }
    }
    
    [self.userTypeTableView reloadData];
}

- (NSMutableArray *)getUserDatasFromLocalJsonWithKey:(NSString *)parentIdKey
{
    NSMutableArray *typeArrays = [[[NSMutableArray alloc] init] autorelease];
    
    NSString *file = [[NSBundle mainBundle] pathForResource:@"mode_sidebar" ofType:@"json"];
    NSString *string = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
    NSDictionary *result = [string objectFromJSONString];
    NSString *status = [result objectForKey:@"status"];
    if ([status isEqualToString:@"200"])
    {
        NSArray *array = [result objectForKey:@"array"];
        for (int i=0; i<array.count; i++)
        {
            NSDictionary *dic = [array objectAtIndex:i];
            NSString *parentId = [dic objectForKey:@"parentId"];
            if ([parentId isEqualToString:parentIdKey])//找出一级目录
            {
                NSString *name = [dic objectForKey:@"name"];
                if ((![name isEqualToString:@"首页"]) && (![name isEqualToString:@"周边商品"]))
                {
                    if (![name isEqualToString:@"全部"])
                    {
                        KeyValueObject *item = [[KeyValueObject alloc] init];
                        item.key = [dic objectForKey:@"selfId"];
                        item.keyDispName = name;
                        item.value = parentId;
                        [typeArrays addObject:item];
                        DLog(@"selfId:%@,name:%@,parentId:%@",item.key,item.keyDispName,item.value);
                        [item release];
                    }
                }
            }
        }
    }
    
    return typeArrays;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 901)
    {
        return self.userTypeDatas.count;
    }
    else
    {
        return self.typeDetailDatas.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 901)
    {
        static NSString *reTypeCellIdentifier = @"reTypeCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reTypeCellIdentifier];
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reTypeCellIdentifier] autorelease];
            cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"register_type.png"]] autorelease];
            
            cell.textLabel.font = [UIFont systemFontOfSize:14.0];
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.highlightedTextColor = [UIColor blackColor];
        }
        
        KeyValueObject *item = [self.userTypeDatas objectAtIndex:indexPath.row];
        cell.textLabel.text = item.keyDispName;
        
        return cell;
    }
    else
    {
        static NSString *typeDetailCellIdentifier = @"typeDetailCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:typeDetailCellIdentifier];
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:typeDetailCellIdentifier] autorelease];
            cell.textLabel.font = [UIFont systemFontOfSize:14.0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        KeyValueObject *item = [self.typeDetailDatas objectAtIndex:indexPath.row];
        cell.textLabel.text = item.keyDispName;
        
        return cell;
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 901)
    {
        if (self.selectedFatherRow == -1)
        {
            self.selectedFatherRow = indexPath.row;
        }
        else if (self.selectedFatherRow != indexPath.row)
        {
            self.selectedTypes = nil;
            self.selectedFatherRow = indexPath.row;
        }
        
        KeyValueObject *item = [self.userTypeDatas objectAtIndex:indexPath.row];
        if (self.typeDetailDatas)
        {
            self.typeDetailDatas = nil;
        }
        self.typeDetailDatas = [self getUserDatasFromLocalJsonWithKey:item.key];
        [self.typeDetailTableView reloadData];
    }
    else
    {
        UITableViewCell *typeCell = [tableView cellForRowAtIndexPath:indexPath];
        if (typeCell.accessoryType == UITableViewCellAccessoryNone)
        {
            typeCell.accessoryType = UITableViewCellAccessoryCheckmark;
            
            if (self.selectedTypes == nil)
            {
                self.selectedTypes = [[[NSMutableArray alloc] init] autorelease];
            }
            KeyValueObject *item = [self.typeDetailDatas objectAtIndex:indexPath.row];
            [self.selectedTypes addObject:item];
        }
        else
        {
            typeCell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
}

@end